// pages/my/ownerValidate.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "业主认证", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent'
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    // 姓名
    name: '',
    // 电话
    phone: '',
    //证件类型
    papersList: [{
      id: 0,
      name: '身份证'
    }, {
      id: 1,
      name: '营业执照'
    }, {
      id: 2,
      name: '护照'
    }, {
      id: 3,
      name: '军官证'
    }, {
      id: 4,
      name: '台胞证'
    }, {
      id: 5,
      name: '港澳通行证'
    }, {
      id: 6,
      name: '其他'
    }],
    cardNum: '',
    papers: '请选择证件类型',
    //组团
    group: '请选择组团',
    groupId: 0,
    groupList: [],

    showArray: [
      [],
      [],
      []
    ], //展示数据
    array: [
      [],
      [],
      []
    ], // 数据数组，分别对应三级联动的数据
    city: ['请选择房号', '', ''], // 默认选中的值
    curBuildId: 0, //当前楼栋Id

    //单元
    buildingList: [],
    //楼栋
    unitList: [],
    //房号
    roomList: [],
    //选择的下标
    chooseRow: [],

    //验证码
    code: '',
    codeDjs: 0,

    openid: '',
    shareTitle: "",
    shareImg: "",
    is_register: 0,
    mySf: '',
    tipsContent: '',
    sendTel: '', //发送验证码的手机号
  },

  // 姓名
  nameIpt(e) {
    this.setData({
      name: e.detail.value
    })
  },
  // 电话
  phoneIpt(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  // 验证码
  codeIpt(e) {
    this.setData({
      code: e.detail.value
    })
  },
  //证件类型
  papersChange(e) {
    let that = this;
    that.setData({
      papers: that.data.papersList[e.detail.value].name,
    })
  },
  //证件号码
  cardNumIpt(e) {
    this.setData({
      cardNum: e.detail.value
    })
  },
  //组团
  groupChange(e) {
    let that = this;
    that.setData({
      group: that.data.groupList[e.detail.value].name,
      groupId: that.data.groupList[e.detail.value].id,
      city: ['请选择房号', '', '']
    });

    //后台更新楼栋单元房号信息
    that.changeInfo(0, that.data.groupId, 0, 0);
  },

  //更新楼栋单元房号 flag=0 用户选择了组团 flag=1用户选择楼栋或单元
  changeInfo(flag, groupId, buildingId, unitId) {
    var that = this;
    var array = that.data.array;
    var showArray = that.data.showArray;
    wx.showLoading({
      title: '房号更新中...',
      mask: true
    });
    wx.request({
      url: that.data.baseUrl + 'changeInfo.php',
      method: 'POST',
      data: {
        flag: flag,
        groupId: groupId,
        buildingId: buildingId,
        unitId: unitId
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //判断是更新的初始数据还是用户的选择
          if (flag == 0) {
            array[0] = res.data.buildingList;
            array[1] = res.data.unitList;
            array[2] = res.data.roomList;
            showArray[0] = res.data.buildingList.map((item) => {
              return item.name
            })
            showArray[1] = res.data.unitList.map((item) => {
              return item.name
            })
            showArray[2] = res.data.roomList.map((item) => {
              return item.name
            })
            that.setData({
              buildingList: res.data.buildingList,
              unitList: res.data.unitList,
              roomList: res.data.roomList,
              array: array,
              showArray: showArray
            });
            console.log("array:", array)
          } else if (flag == 1) {
            array[1] = res.data.unitList;
            array[2] = res.data.roomList;
            showArray[1] = res.data.unitList.map((item) => {
              return item.name
            })
            showArray[2] = res.data.roomList.map((item) => {
              return item.name
            })
            //用户选择
            that.setData({
              unitList: res.data.unitList,
              roomList: res.data.roomList,
              array: array,
              showArray: showArray
            });
          } else {
            array[2] = res.data.roomList;
            showArray[2] = res.data.roomList.map((item) => {
              return item.name
            })
            //用户选择
            that.setData({
              roomList: res.data.roomList,
              array: array,
              showArray: showArray
            });
          }
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function(res) {
        wx.hideLoading();
        app.showTip('服务器繁忙,请稍候重试');
      }
    });
  },


  bindChange: function(e) {
    const val = e.detail.value;
    this.setData({
      city: [
        this.data.array[0][val[0]].name,
        this.data.array[1][val[1]].name,
        this.data.array[2][val[2]].name
      ],
      chooseRow: val
    });
  },

  bindColumnChange: function(e) {
    let that = this;
    const col = e.detail.column;
    const val = e.detail.value;
    const array = that.data.array;
    console.log("滑动：", e)

    console.log("array2:", array)
    // 根据选择的建筑更新单元和楼层数据
    if (col === 0) {
      that.setData({
        curBuildId: array[0][val].id
      })
      console.log("当前楼栋Id：", that.data.curBuildId)
      // 假设根据建筑动态加载单元和楼层数据的函数
      that.changeInfo(1, that.data.groupId, array[0][val].id, 0);
    }
    if (col === 1) {
      console.log("当前楼栋Id：", that.data.curBuildId)
      console.log("当前单元Id：", array[1][val].id)
      console.log("滑动列：", that.data.curBuildId)
      // 假设根据建筑动态加载单元和楼层数据的函数
      that.changeInfo(2, that.data.groupId, that.data.curBuildId, array[1][val].id);
    }
  },

  //房号
  roomNumChange(e) {
    let that = this;
    that.setData({
      roomNum: that.data.roomNumList[e.detail.value].name,
    })
  },

  //发送验证码
  sendCode() {
    let that = this;
    //判断是否注册登录过
    if (that.data.is_register == 0) {
      //还未注册登录过
      wx.showModal({
        title: '温馨提示',
        content: that.data.tipsContent,
        complete: (res) => {
          if (res.confirm) {
            //跳转注册界面
            wx.setStorageSync('loginHeaderUrl', '/pages/my/ownerValidate');
            wx.setStorageSync('loginHeaderType', 'redirectTo');
            if (res.confirm) {
              //跳转注册界面
              wx.redirectTo({
                url: '/pages/login/index'
              });
            }
          }
        }
      })
      return;

    }
    //判断是否重复点击
    if (that.data.codeDjs > 0 && that.data.codeDjs < 60) {
      return;
    }
    if (that.data.phone.trim() === '') {
      app.showTip("请输入电话")
    } else if (that.data.phone.trim().length != 11) {
      app.showTip("请输入正确的电话")
    } else {

      //后台请求发送验证码
      wx.showLoading({
        title: '验证码发送中...'
      });
      wx.request({
        url: that.data.baseUrl + 'sendCode.php',
        method: 'POST',
        data: {
          openid: that.data.openid,
          tel: that.data.phone.trim()
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          wx.hideLoading();
          app.showTip(res.data.msg);
          if (res.data.status == 1) {
            that.setData({
              sendTel: res.data.sendTel
            });
            //处理时间
            that.setData({
              codeDjs: 60
            })
            let interval = setInterval(function() {
              if (that.data.codeDjs > 0) {
                that.data.codeDjs--;
                console.log(that.data.codeDjs)
                that.setData({
                  codeDjs: that.data.codeDjs
                })
              } else {
                clearInterval(interval);
              }
            }, 1000);
          }
        },
        fail: function(res) {
          wx.hideLoading();
          app.showTip('服务器繁忙,请稍候重试');
        }
      });
    }
  },
  //点击验证
  yz() {
    let that = this;
    //判断是否注册登录过
    if (that.data.is_register == 0) {
      //还未注册登录过
      wx.showModal({
        title: '温馨提示',
        content: that.data.tipsContent,
        complete: (res) => {
          if (res.confirm) {
            //跳转注册界面
            wx.setStorageSync('loginHeaderUrl', '/pages/my/ownerValidate');
            wx.setStorageSync('loginHeaderType', 'switchTab');
            if (res.confirm) {
              //跳转注册界面
              wx.redirectTo({
                url: '/pages/login/index'
              });
            }
          }
        }
      })
      return;
    }

    var chooseRow = that.data.chooseRow;
    if (that.data.name.trim() === '') {
      app.showTip('请输入姓名');
    } else if (that.data.phone.trim() === '') {
      app.showTip('请输入电话');
    } else if (isNaN(that.data.phone) || that.data.phone.length !== 11) {
      app.showTip('请输入正确电话');
    } else if (that.data.code.trim() === '') {
      app.showTip("请输入验证码");
    } else if (that.data.code.trim().length != 6 || isNaN(that.data.code.trim())) {
      app.showTip("请输入6位数字的验证码");
    } else if (that.data.sendTel != that.data.phone.trim() && that.data.sendTel != '') {
      app.showTip("抱歉,您提交的电话号码和发送短信的电话号码不一致");
    } else if (that.data.papers.trim() === '请选择证件类型') {
      app.showTip('请选择证件类型');
    } else if (that.data.cardNum.trim() === '请输入证件号码') {
      app.showTip('请输入证件号码');
    } else if (that.data.groupId === 0) {
      app.showTip('请选择组团');
    } else if (chooseRow.length == 0) {
      app.showTip('请选择房号');
      return;
    } else {
      wx.showLoading({
        title: '数据提交中...'
      });
      //获取用户选择的楼栋单元房号
      var building = that.data.array[0][chooseRow[0]].id;
      var unit = that.data.array[1][chooseRow[1]].id;
      var room = that.data.array[2][chooseRow[2]].id;

      wx.request({
        url: that.data.baseUrl + 'checkYzrz.php',
        method: 'POST',
        data: {
          openid: that.data.openid,
          name: that.data.name.trim(),
          tel: that.data.phone.trim(),
          code: that.data.code.trim(),
          id_type: that.data.papers.trim(),
          id_card: that.data.cardNum.trim(),
          team: that.data.groupId,
          building: building,
          unit: unit,
          room: room
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          wx.hideLoading();
          if (res.data.status == 1) {
            //app.showTip(res.data.msg);
             wx.showModal({
              title: '温馨提示',
              content: res.data.msg,//editable如果为true，这就是输入框的内容
              success (res) {
      
              }
            });
            setTimeout(function() {
              wx.switchTab({
                url: '/pages/my/index'
              });
            }, 1500)
          } else if (res.data.status == 100) {
            //需要人工审核 弹窗提示
            //app.showTip(res.data.msg);
            wx.showModal({
              title: '温馨提示',
              content: res.data.msg,//editable如果为true，这就是输入框的内容
              success (res) {
      
              }
            });
            setTimeout(function () {
              wx.switchTab({
                url: '/pages/my/index'
              });
            }, 2000)
          } else {
            //app.showTip(res.data.msg);
            wx.showModal({
              title: '温馨提示',
              content: res.data.msg,//editable如果为true，这就是输入框的内容
              success (res) {
      
              }
            });
          }
        },
        fail: function(res) {
          wx.hideLoading();
          app.showTip('服务器繁忙,请稍候重试');
        }
      });

    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function(res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function(res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getYzrzPageInfo(res.data.openid);
              },
              fail: function(res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getYzrzPageInfo(openid);
    }

    //调用分享
    that.getShareInfo();
  },

  //获取本页数据
  getYzrzPageInfo(openid) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...'
    })
    wx.request({
      url: that.data.baseUrl + 'getYzrzPageInfo.php',
      method: 'POST',
      data: {
        'openid': openid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.status == 1) {

          //重新赋值后台请求数据
          that.setData({
            mySf: res.data.mySf,
            is_register: res.data.is_register,
            tipsContent: res.data.tipsContent,
            groupList:res.data.groupList
          });
        } else {
          app.showTip(res.data.msg);
          setTimeout(function() {
            wx.navigateBack({
              delta: 1
            });
          }, 2000);
        }
      },
      fail: function() {
        wx.hideLoading();
        app.showTip('抱歉,服务器繁忙');
        setTimeout(function() {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
      }
    });
  },


  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function(res) {}
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/index/index',
      imageUrl: that.data.shareImg,
      success: function(res) {

      },
      fail: function(res) {

      }
    }
  }
})